package org.gd.exercise.learnspringbootredis.controller;

import io.lettuce.core.ScriptOutputType;
import org.gd.exercise.learnspringbootredis.dto.CartResultDTO;
import org.gd.exercise.learnspringbootredis.dto.GoodsDTO;
import org.gd.exercise.learnspringbootredis.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author name: yushanjiang
 * @version 1.0
 * @description: redis的Hash类型应用场景
 * @date 2025/9/12 11:26
 */
@RestController
@RequestMapping("/hash")
public class HashController {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
    * @description: 场景1-缓存对象
    * @param: [userId, userInfo]
    * @return java.lang.String
    * @author name: yushanjiang
    * @date: 2025/9/12 12:33
    */
    @PostMapping("/cache/user/{userId}")
    public String cacheUser(@PathVariable String userId,
                            @RequestBody UserDTO userInfo) {
        String cacheKey = "jys_user:hashcache:{" + userId + "}";
        System.out.println("要缓存的用户ID：" + userId);
        redisTemplate.opsForHash().put(cacheKey, "name", userInfo.getName());
        redisTemplate.opsForHash().put(cacheKey, "age", userInfo.getAge());
        redisTemplate.opsForHash().put(cacheKey, "phone", userInfo.getPhone());
        return "缓存成功！userId=" + userId + "，缓存的信息：" + userInfo;
    }

    /**
    * @description: 场景1-缓存对象-获取对象
    * @param: [userId]
    * @return org.gd.exercise.learnspringbootredis.dto.UserDTO
    * @author name: yushanjiang
    * @date: 2025/9/12 13:34
    */
    @GetMapping("/cache/getuser/{userId}")
    public UserDTO getUser(@PathVariable String userId) {
        String cacheKey = "jys_user:hashcache:{" + userId + "}";
        UserDTO userInfo = new UserDTO();
        userInfo.setName((String) redisTemplate.opsForHash().get(cacheKey, "name"));
        userInfo.setAge((Integer) redisTemplate.opsForHash().get(cacheKey, "age"));
        userInfo.setPhone((String) redisTemplate.opsForHash().get(cacheKey, "phone"));
        return userInfo;
    }

    /**
    * @description: 场景2-电商购物车-新增商品
    * @param: [userId, goodsId]
    * @return java.lang.String
    * @author name: yushanjiang
    * @date: 2025/9/12 13:55
    */
    @PostMapping("/shoppingcar/addgoods/{userId}/{goodsId}")
    public String addGooods(@PathVariable String userId,
                            @PathVariable String goodsId) {
        String key = "jys_shoppingcar:user:" + userId;
        String field = "goods:" + goodsId;
        System.out.println("要操作的key:" + key);
        System.out.println("要操作的field:" + field);
        redisTemplate.opsForHash().increment(key, field, 1);
        return "新增商品成功！商品ID：" + goodsId;
    }


    /**
    * @description: 场景2-电商购物车-获取购物车所有商品、购物车中商品数量
    * @param: [userId]
    * @return org.gd.exercise.learnspringbootredis.dto.CartResultDTO
    * @author name: yushanjiang
    * @date: 2025/9/12 14:48
    */
    @GetMapping("/shoppingcar/getgoods/{userId}")
    public CartResultDTO getGoods(@PathVariable String userId) {
        String key = "jys_shoppingcar:user:" + userId;
        // 获取购物车中商品种类数，即该key对应的哈希表中键值对数量
        Long totalCount = redisTemplate.opsForHash().size(key);
        // 获取该用户购物车的所有商品，即该key对应的哈希表中所有键值对
        Map<Object, Object> redisMap = redisTemplate.opsForHash().entries(key);

        Map<String, Integer> goodsMap = new HashMap<>();

        redisMap.entrySet().stream().forEach(entry -> {
            // 完成Map<Object, Object> redisMap 到 Map<String, Integer> goodsMap类型的转换
            String goodsId = (String) entry.getKey();
            Integer goodsCount = (Integer) entry.getValue();

            goodsMap.put(goodsId, goodsCount);
        });

        CartResultDTO cartResultDTO = new CartResultDTO();
        cartResultDTO.setGoodsMap(goodsMap);
        cartResultDTO.setTotalCount(totalCount);
        return cartResultDTO;
    }
    /**
    * @description: 场景2-电商购物车-删除商品
    * @param: [userId, goodsId]
    * @return java.lang.String
    * @author name: yushanjiang
    * @date: 2025/9/12 16:25
    */
    @PostMapping("/shoppingcar/delgoods/{userId}/{goodsId}")
    public String delGoods(@PathVariable String userId,
                           @PathVariable String goodsId) {
        String key = "jys_shoppingcar:user:" + userId;
        String field = "goods:" + goodsId;
        redisTemplate.opsForHash().delete(key, field);
        return "删除成功！已删除ID为：" + goodsId + "的商品";
    }
}
